//
//  SCPhotoAlbumListViewController.m
//  PhotoAlbum
//
//  Created by Chao Sheng on 2021/12/1.
//

#import "SCPhotoAlbumListViewController.h"
#import "SCPhotoTools.h"
#import "SCPhotoAlbumSectionHeader.h"
#import "SCPhotoAlbumPreviewViewController.h"

/// 自定义FlowLayout，实现setionHeader悬浮效果,同时实现悬浮时setionHeader的毛玻璃效果
@interface SCPhotoAlbumFlowLayout : UICollectionViewFlowLayout

@property (assign, nonatomic) BOOL hasSuspension;

@end

@implementation SCPhotoAlbumFlowLayout

- (NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    NSArray *array = [super layoutAttributesForElementsInRect:rect];
    NSMutableArray *answer = [array mutableCopy];
    
    UICollectionView * const cv = self.collectionView;
    CGPoint const contentOffset = cv.contentOffset;

    NSMutableIndexSet *missingSections = [NSMutableIndexSet indexSet];
    for (UICollectionViewLayoutAttributes *layoutAttributes in answer) {
        if (layoutAttributes.representedElementCategory == UICollectionElementCategoryCell) {
            [missingSections addIndex:layoutAttributes.indexPath.section];
        }
    }
    for (UICollectionViewLayoutAttributes *layoutAttributes in answer) {
        if ([layoutAttributes.representedElementKind isEqualToString:UICollectionElementKindSectionHeader]) {
            [missingSections removeIndex:layoutAttributes.indexPath.section];
        }
    }

    [missingSections enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:idx];
        UICollectionViewLayoutAttributes *layoutAttributes = [self layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader atIndexPath:indexPath];

        [answer addObject:layoutAttributes];
    }];
    
    for (UICollectionViewLayoutAttributes *layoutAttributes in answer) {
        if ([layoutAttributes.representedElementKind isEqualToString:UICollectionElementKindSectionHeader]) {
            
            NSInteger section = layoutAttributes.indexPath.section;
            NSInteger numberOfItemsInSection = [cv numberOfItemsInSection:section];
            
            NSIndexPath *firstObjectIndexPath = [NSIndexPath indexPathForItem:0 inSection:section];
            NSIndexPath *lastObjectIndexPath = [NSIndexPath indexPathForItem:MAX(0, (numberOfItemsInSection - 1)) inSection:section];
            
            UICollectionViewLayoutAttributes *firstObjectAttrs;
            UICollectionViewLayoutAttributes *lastObjectAttrs;
            
            if (numberOfItemsInSection > 0) {
                firstObjectAttrs = [self layoutAttributesForItemAtIndexPath:firstObjectIndexPath];
                lastObjectAttrs = [self layoutAttributesForItemAtIndexPath:lastObjectIndexPath];
            } else {
                firstObjectAttrs = [self layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader atIndexPath:firstObjectIndexPath];
                lastObjectAttrs = [self layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionFooter atIndexPath:lastObjectIndexPath];
            }
            
            CGFloat headerHeight = CGRectGetHeight(layoutAttributes.frame);
            CGPoint origin = layoutAttributes.frame.origin;
            CGFloat topY = contentOffset.y + cv.contentInset.top;
            CGFloat normalY = (CGRectGetMinY(firstObjectAttrs.frame) - headerHeight);
            CGFloat missingY = (CGRectGetMaxY(lastObjectAttrs.frame) - headerHeight);
            
            CGFloat max = MAX(topY, normalY);
            CGFloat min = MIN(max, missingY);
            
            if (topY >= normalY && topY <= missingY + headerHeight) {
                if (@available(iOS 9 ,*)) {
                    SCPhotoAlbumSectionHeader *headerView = (SCPhotoAlbumSectionHeader *)[cv supplementaryViewForElementKind:UICollectionElementKindSectionHeader atIndexPath:layoutAttributes.indexPath];
                    if (headerView) {
                        headerView.translucent = YES;
                    }
                }
                self.hasSuspension = YES;
            }else {
                if (@available(iOS 9 ,*)) {
                    SCPhotoAlbumSectionHeader *headerView = (SCPhotoAlbumSectionHeader *)[cv supplementaryViewForElementKind:UICollectionElementKindSectionHeader atIndexPath:layoutAttributes.indexPath];
                    if (headerView) {
                        headerView.translucent = NO;
                    }
                }
                self.hasSuspension = NO;
            }
            if (origin.y != min && self.hasSuspension) {
                origin.y = min;
                layoutAttributes.zIndex = 1024;
                layoutAttributes.frame = (CGRect){
                    .origin = origin,
                    .size = layoutAttributes.frame.size
                };
            }
        }
    }
    return answer;
}

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
    return YES;
}

@end


@interface SCPhotoAlbumListViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UIViewControllerTransitioningDelegate>

@property (nonatomic, strong) NSArray<SCPhotoDateModel*>*dateList;

@property (nonatomic, strong) NSArray<SCPhotoModel *> *photoList;

@property (nonatomic, assign) NSInteger photoCount;

@property (nonatomic, assign) BOOL clickPreviewCompletion;

@end

@implementation SCPhotoAlbumListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBar.translucent = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    if (@available(iOS 15, *)) {
        UINavigationBarAppearance *appearance = [[UINavigationBarAppearance alloc] init];
        appearance.shadowColor = [UIColor clearColor];
        appearance.shadowImage = [SCPhotoTools imageLineWithColor:[UIColor colorWithWhite:0.8 alpha:0.5]];
        self.navigationController.navigationBar.scrollEdgeAppearance = appearance;// 带scroll滑动的页面
        self.navigationController.navigationBar.standardAppearance = appearance;// 常规页面
    }
    
    [SCPhotoTools requestAuthorization:self type:@"photo"];
    
    [self setupUI];
    [self getPhotoList];
    self.title = @"我的相册";
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(didCancelClick)];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}

- (void)setupUI {
    [self.view addSubview:self.collectionView];
    
    [self.view addSubview:self.bottomView];
    [self updateBottomTitle:self.manager.selectedArray];
    sc_weak(self);
    //预览操作
    self.bottomView.scBottomPreview = ^{
        SCPhotoAlbumPreviewViewController *vc = [SCPhotoAlbumPreviewViewController new];
        vc.photoList = weakself.manager.selectedArray;
        vc.currentModelIndex = 0;
        vc.manager = weakself.manager;
        vc.selectedIndex = 1;
        
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
        nav.modalPresentationStyle = 0;
        [weakself presentViewController:nav animated:YES completion:nil];
    };
    //点击完成后操作
    self.bottomView.scBottomCompltion = ^{
        if (weakself.scSelectCompletion) {
            weakself.scSelectCompletion();
        }
        [weakself dismissViewControllerAnimated:YES completion:nil];
//        if (weakself.manager.ocrEnable && [weakself neetOcrImageText]) {
//            [MBProgressHUD showSCLoadind:@"正在识别，请稍后..."];
//            [[SCHWCloudManager shareInstance] ocrImages:weakself.manager.selectedArray success:^{
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    [MBProgressHUD hideSCHud];
//                    if (weakself.scSelectCompletion) {
//                        weakself.scSelectCompletion();
//                    }
//                    [weakself dismissViewControllerAnimated:YES completion:nil];
//                });
//            } failure:^(NSError * _Nonnull error) {
//
//            }];
//        } else {
//            if (weakself.scSelectCompletion) {
//                weakself.scSelectCompletion();
//            }
//            [weakself dismissViewControllerAnimated:YES completion:nil];
//        }
    };
}

- (void)setManager:(SCPhotoManager *)manager {
    _manager = manager;
}

- (void)didCancelClick {
    
    self.manager.selectedArray = self.manager.oldSelectedArray.mutableCopy;
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

//判断是否需要识别图片中的文字
- (BOOL)neetOcrImageText {
    BOOL need = NO;
    for (SCPhotoModel *model in self.manager.selectedArray) {
        if(!model.ocrTextUsed) {
            need = YES;
            break;
        }
    }
    return need;
}

//获取系统所有相册
- (void)getPhotoList {
    
    self.dateList = @[].mutableCopy;
    sc_weak(self);
    [self.manager getAllPhotoAlbumListByDateCompletion:^(NSArray<SCPhotoDateModel *> * _Nonnull dateList, NSArray<SCPhotoModel *> * _Nonnull photoList, NSInteger count) {
        weakself.dateList = dateList.copy;
        weakself.photoList = photoList.copy;
        weakself.photoCount = count;

        //处理网络图片和拍摄照片数据存储到数组中
        NSMutableArray *newImglist = @[].mutableCopy;
        for (SCPhotoModel *m in weakself.manager.selectedArray) {
            if (m.imageNetworkingUrl && !m.asset) {
                [newImglist addObject:m];
            } else if (m.isCamera) {
                [newImglist addObject:m];
            }
        
        }
        if (newImglist.count>0) {
            SCPhotoDateModel *dateM = weakself.dateList.lastObject;
            NSMutableArray *datePList = [NSMutableArray arrayWithArray:dateM.photoList];
            NSMutableArray *pList = [NSMutableArray arrayWithArray:weakself.photoList];
            for (NSInteger i = 0; i<newImglist.count; i++) {
                SCPhotoModel *m = newImglist[i];
                m.section = dateM.photoList.firstObject.section;
                m.row = dateM.photoList.firstObject.row+i+1;
                [datePList addObject:m];
                [pList addObject:m];
            }
            dateM.photoList = datePList.copy;
            weakself.photoList = pList.copy;
            weakself.photoCount = pList.count;
            
        }
        //刷新列表
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.collectionView reloadData];
            if(self.dateList.count>0 && self.dateList.lastObject.photoList.count>0) {
                [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:self.dateList.lastObject.photoList.count-1 inSection:self.dateList.count-1] atScrollPosition:UICollectionViewScrollPositionBottom animated:NO];
            }
        });
    }];
    
}

// 根据model获取当期cell
- (SCPhotoCell *)currentPhotoCell:(SCPhotoModel *)model {
    
    if (!model || ![self.photoList containsObject:model]) {
        return  nil;
    }
    
    SCPhotoCell *cell = (SCPhotoCell*)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:model.row inSection:model.section]];
    
    return cell;
}

// 滚动到相应位置
- (void)scrollToPoint:(SCPhotoCell *)cell rect:(CGRect)rect {
   
    CGFloat navBarHeight = sc_NAVIGATION_HEIGHT;
    if (rect.origin.y < navBarHeight+50) {
        [self.collectionView setContentOffset:CGPointMake(0, cell.frame.origin.y - navBarHeight - 50)];
    }else if (rect.origin.y + rect.size.height > self.view.frame.size.height - 50.5 - sc_BOTTOMPADDING_HEIGHT) {
        [self.collectionView setContentOffset:CGPointMake(0, cell.frame.origin.y - self.view.frame.size.height + 50.5 + sc_BOTTOMPADDING_HEIGHT + rect.size.height)];
    }
}

// 判断当期位置model的cell是否存在
- (BOOL)scrollToModel:(SCPhotoModel *)model {
    
    if ([self.photoList containsObject:model]) {
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:model.row inSection:model.section] atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO];
        [self.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:model.row inSection:model.section]]];
    }
    return [self.photoList containsObject:model];
}

//更新bottom上的按钮文字
- (void)updateBottomTitle:(NSArray*)array {
    self.bottomView.selectedCount = array.count;
}

#pragma mark - delegate & dataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.dateList.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    SCPhotoDateModel *dateModel = self.dateList[section];
    return dateModel.photoList.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SCPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SCPhotoCell" forIndexPath:indexPath];
    cell.photoModel = self.dateList[indexPath.section].photoList[indexPath.row];
    cell.photoModel.row = indexPath.row;
    cell.photoModel.section = indexPath.section;
    cell.manager = self.manager;
    sc_weak(self);
    cell.scSelectedCompltion = ^(SCPhotoModel * _Nonnull photoModel) {
        
        [weakself updateBottomTitle:weakself.manager.selectedArray];

        NSMutableArray *indexPaths = @[].mutableCopy;
        for (SCPhotoModel *model in weakself.manager.selectedArray) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:model.row inSection:model.section];
            [indexPaths addObject:indexPath];
        }
        [weakself.collectionView reloadItemsAtIndexPaths:indexPaths];
    };
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    SCPhotoAlbumPreviewViewController *vc = [SCPhotoAlbumPreviewViewController new];
    vc.photoList = self.photoList;
    SCPhotoModel *photoModel = self.dateList[indexPath.section].photoList[indexPath.row];
    vc.currentModelIndex = [self.photoList indexOfObject:photoModel];
    vc.manager = self.manager;
    vc.selectedIndex = photoModel.selectedIndex;
    sc_weak(self);
    vc.scCompletion = ^{ 
        if(weakself.scSelectCompletion) {
            weakself.scSelectCompletion();
        }
        weakself.clickPreviewCompletion = true;//转场动画时调用
    };
    
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    nav.modalPresentationStyle = 0;
    nav.transitioningDelegate = self;

    [self presentViewController:nav animated:YES completion:nil];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(sc_WIDTH, 50);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    
    if (section==self.dateList.count-1) {
        return CGSizeMake(sc_WIDTH, 50);
    } else {
        return CGSizeZero;
    }
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        SCPhotoAlbumSectionHeader *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"SCPhotoAlbumSectionHeader" forIndexPath:indexPath];
        SCPhotoDateModel *dateModel = self.dateList[indexPath.section];
        headerView.dateStr = dateModel.dateName;
        return headerView;
    }
    else if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
        SCPhotoAlbumSectionFooter *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"SCPhotoAlbumSectionFooter" forIndexPath:indexPath];
        footerView.photoCount = self.photoCount;
        return footerView;
    }
    return nil;
}

#pragma mark - 转场动画
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source {
    SCPhotoPreviewPresentAnimationTransition *anim = [[SCPhotoPreviewPresentAnimationTransition alloc] initWithPresentTransitionType:SCTransitionPresentType photoView:nil];
    return anim;
}

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed {
    if (!self.clickPreviewCompletion) {
        SCPhotoPreviewPresentAnimationTransition *anim = [[SCPhotoPreviewPresentAnimationTransition alloc] initWithPresentTransitionType:SCTransitionDismissType photoView:nil];
        return anim;
    } else {
        SCPhotoPreviewPresentAnimationTransition *anim = [[SCPhotoPreviewPresentAnimationTransition alloc] initWithPresentTransitionType:SCTransitionNoneType photoView:nil];
        return anim;
    }
}

#pragma mark - 懒加载
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        SCPhotoAlbumFlowLayout *flowLayout = [[SCPhotoAlbumFlowLayout alloc] init];
        flowLayout.minimumLineSpacing = 1;
        flowLayout.minimumInteritemSpacing = 1;
        flowLayout.sectionInset = UIEdgeInsetsMake(0.5, 0, 0.5, 0);
        CGFloat width = sc_WIDTH;
        CGFloat itemWidth = (width - (self.manager.rowCount - 1)) / self.manager.rowCount;
        CGFloat itemHeight = itemWidth;
        flowLayout.itemSize = CGSizeMake(itemWidth, itemHeight);
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0,sc_WIDTH,sc_HEIGHT-sc_BOTTOMPADDING_HEIGHT) collectionViewLayout:flowLayout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor whiteColor];
        [_collectionView registerClass:[SCPhotoCell class] forCellWithReuseIdentifier:@"SCPhotoCell"];
        [_collectionView registerClass:[SCPhotoAlbumSectionHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SCPhotoAlbumSectionHeader"];
        [_collectionView registerClass:[SCPhotoAlbumSectionFooter class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"SCPhotoAlbumSectionFooter"];
        if (@available(iOS 11.0, *)) {
            _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        _collectionView.contentInset = UIEdgeInsetsMake(sc_NAVIGATION_HEIGHT, 0, sc_BOTTOMPADDING_HEIGHT+50, 0);
    }
    return _collectionView;
}

- (SCPhotoAlbumBottomView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[SCPhotoAlbumBottomView alloc] initWithFrame:CGRectMake(0,sc_HEIGHT-sc_BOTTOMPADDING_HEIGHT-50, sc_WIDTH,sc_BOTTOMPADDING_HEIGHT+50)];
        _bottomView.maxCount = self.manager.photoSelectedMax;
    }
    return _bottomView;
}

- (void)dealloc {
    NSLog(@"列表释放");
}

@end
